import React from "react";
import { useEffect, useRef } from "react";

function drawDotGrid(canvas: HTMLCanvasElement) {
  const width = window.innerWidth;
  const height = window.innerHeight;
  canvas.width = width || 500;
  canvas.height = height || 500;
  const gridSpacing = 20;
  const dotRadius = 1;
  const dotColor = "rgba(0, 0, 0, 0.2)";
  const ctx: any = canvas.getContext("2d");
  for (let x = 0; x < width; x += gridSpacing) {
    for (let y = 0; y < height; y += gridSpacing) {
      ctx.beginPath();
      ctx.arc(x, y, dotRadius, 0, 2 * Math.PI, false);
      ctx.fillStyle = dotColor;
      ctx.fill();
    }
  }
}

export default function () {
  const canvasEl = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    window.addEventListener("resize", () => drawDotGrid(canvasEl.current as HTMLCanvasElement));
    drawDotGrid(canvasEl.current as HTMLCanvasElement);
    return () => {
      window.removeEventListener("resize", () => drawDotGrid(canvasEl.current as HTMLCanvasElement));
    };
  }, []);

  return (
    <div style={{ position: "absolute", width: "100%", height: "100%", top: 0, zIndex: -1 }}>
      <canvas ref={canvasEl} />
    </div>
  );
}
